package com.jiawa.wordgz;

import org.apache.commons.io.FileUtils;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.Document;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.xmlbeans.XmlException;
import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing;

import java.io.*;
import java.lang.ref.WeakReference;
import java.util.List;
import java.util.Random;



//一个地方盖章

/**
 * 插入图片
 */
public class DocxImg {
    /**
     * <b> Word中添加图章
     * </b><br><br><i>Description</i> :
     * String srcPath, 源Word路径
     * String storePath, 添加图章后的路径
     * String sealPath, 图章路径（即图片）
     * tString abText, 在Word中盖图章的标识字符串，如：(签字/盖章)
     * int width, 图章宽度
     * int height, 图章高度
     * int leftOffset, 图章在编辑段落向右偏移量
     * int topOffset, 图章在编辑段落向上偏移量
     * boolean behind，图章是否在文字下面
     */
    public static void sealInWord(String srcPath, String storePath,String sealPath,String tabText,
                                  int width, int height, int leftOffset, int topOffset, boolean behind) throws Exception {

                    try (FileInputStream is = new FileInputStream(new File(srcPath));
                         XWPFDocument document = new XWPFDocument(is)) {

                        List<XWPFParagraph> paragraphs = document.getParagraphs();
                        XWPFRun targetRun = null;
                        for (XWPFParagraph paragraph : paragraphs) {
                            if (!paragraph.getText().isEmpty() && paragraph.getText().contains(tabText)) {
                                List<XWPFRun> runs = paragraph.getRuns();
                                targetRun = runs.get(runs.size() - 1);
                                break; // 找到后立即跳出循环
                            }
                        }

                        if (targetRun != null) {
                            try (InputStream in = new FileInputStream(sealPath)) {
                                if (width <= 0) width = 100;
                                if (height <= 0) height = 100;
                                Random random = new Random();
                                int number = random.nextInt(999) + 1;
                                targetRun.addPicture(in, Document.PICTURE_TYPE_PNG, "Seal" + number, Units.toEMU(width), Units.toEMU(height));

                                CTDrawing drawing = targetRun.getCTR().getDrawingArray(0);
                                if (drawing != null) {
                                    CTGraphicalObject graphicalobject = drawing.getInlineArray(0).getGraphic();

                                    CTAnchor anchor = getAnchorWithGraphic(graphicalobject, "Seal" + number,
                                            Units.toEMU(width), Units.toEMU(height),
                                            Units.toEMU(leftOffset), Units.toEMU(topOffset), behind);

                                    if (drawing.getInlineArray().length > 0) {
                                        drawing.setAnchorArray(new CTAnchor[]{anchor});
                                        drawing.removeInline(0);
                                    }
                                }
                            }
                        }

                        try (FileOutputStream out = new FileOutputStream(storePath)) {
                            document.write(out);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
    }
    /**
     * @param ctGraphicalObject 图片数据
     * @param deskFileName      图片描述
     * @param width             宽
     * @param height            高
     * @param leftOffset        水平偏移 left
     * @param topOffset         垂直偏移 top
     * @param behind            文字上方，文字下方
     * @return
     * @throws Exception
     */
    public static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject,
                                                String deskFileName, int width, int height,
                                                int leftOffset, int topOffset, boolean behind) {
        System.out.println(">>width>>"+width+"; >>height>>>>"+height);
        String anchorXML =
                "<wp:anchor xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" "
                        + "simplePos=\"0\" relativeHeight=\"0\" behindDoc=\"" + ((behind) ? 1 : 0) + "\" locked=\"0\" layoutInCell=\"1\" allowOverlap=\"1\">"
                        + "<wp:simplePos x=\"0\" y=\"0\"/>"
                        + "<wp:positionH relativeFrom=\"column\">"
                        + "<wp:posOffset>" + leftOffset + "</wp:posOffset>"
                        + "</wp:positionH>"
                        + "<wp:positionV relativeFrom=\"paragraph\">"
                        + "<wp:posOffset>" + topOffset + "</wp:posOffset>" +
                        "</wp:positionV>"
                        + "<wp:extent cx=\"" + width + "\" cy=\"" + height + "\"/>"
                        + "<wp:effectExtent l=\"0\" t=\"0\" r=\"0\" b=\"0\"/>"
                        + "<wp:wrapNone/>"
                        + "<wp:docPr id=\"1\" name=\"Drawing 0\" descr=\"" + deskFileName + "\"/><wp:cNvGraphicFramePr/>"
                        + "</wp:anchor>";

        CTDrawing drawing = null;
        try {
            drawing = CTDrawing.Factory.parse(anchorXML);
        } catch (XmlException e) {
            e.printStackTrace();
        }
        CTAnchor anchor = drawing.getAnchorArray(0);
        anchor.setGraphic(ctGraphicalObject);
        return anchor;
    }
}